<template>
  
  <div class="reg-page">
    <TopHeader title="在线挂号" />
    <div class="reg-header">
      <span>当前就诊人：{{ userStore.userInfo?.realName || '未登录' }}</span>
      <span class="id-link" @click="goToProfile">我的身份码 &gt;</span>
    </div>
    <div class="reg-main">
      <div class="dept-list">
        <div
          v-for="dept in departments"
          :key="dept.departmentId"
          :class="['dept-item', {active: dept.departmentId === activeDeptId}]"
          @click="selectDept(dept.departmentId)"
        >{{ dept.departmentName }}</div>
      </div>
      <div class="reg-content">
        <div class="date-bar">
          <div
            v-for="(date, idx) in dateList"
            :key="date.value"
            :class="['date-item', {active: idx === activeDateIdx}]"
            @click="selectDate(idx)"
          >
            <div>{{ date.label }}</div>
            <div>{{ date.text }}</div>
          </div>
          <el-button class="calendar-btn" @click="showCalendar = true" circle size="small">
            <el-icon><Calendar /></el-icon>
          </el-button>
          <el-date-picker
            v-model="calendarDate"
            v-if="showCalendar"
            type="date"
            style="position:absolute;z-index:9999;left:0;right:0;"
            @change="onCalendarChange"
            @blur="showCalendar = false"
          />
          <el-button size="small" style="margin-left:12px;" :type="showRecommendOnly ? 'primary' : 'default'" @click="showRecommendOnly = true">推荐医生</el-button>
          <el-button size="small" :type="!showRecommendOnly ? 'primary' : 'default'" @click="showRecommendOnly = false">全部医生</el-button>
      </div>
        <div style="display:flex;align-items:center;margin-bottom:10px;">
          <!-- 医生搜索栏已删除 -->
        </div>
        <div class="doctor-list">
          <div
            v-for="doc in filteredDoctors"
            :key="doc.doc_id"
            class="doctor-card"
            @click="openAppointmentDialog(doc)"
          >
            <img :src="doc.img || defaultAvatar" class="doc-avatar" />
            <div class="doc-info">
              <div class="doc-name">{{ doc.doc_name }} <span class="doc-title">{{ doc.doc_title }}</span></div>
              <div class="doc-nums">余号：上午{{ getDoctorWorkLeft(doc, 'am') }} 下午{{ getDoctorWorkLeft(doc, 'pm') }}</div>
            </div>
          </div>
          <div v-if="filteredDoctors.length === 0" style="text-align:center;color:#aaa;margin-top:40px;">暂无医生</div>
        </div>
      </div>
      </div>
    <el-dialog v-model="showDialog" title="预约挂号" width="90%">
      <div v-if="currentDoctor">
        <div style="font-weight:bold;margin-bottom:8px;">{{ currentDoctor.doc_name }} <span style="color:#888;font-size:13px;">{{ currentDoctor.doc_title }}</span></div>
        <el-form :model="form" label-width="70px" ref="formRef">
          <el-form-item label="就诊人">
            <el-input v-model="form.name" readonly />
          </el-form-item>
          <el-form-item label="电话" prop="telephone" :rules="[{ required: true, message: '请输入联系电话' }, { validator: validatePhone, trigger: 'blur' }]">
            <el-input v-model="form.telephone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="日期">
            <el-input v-model="form.day" readonly />
          </el-form-item>
          <el-form-item label="时段">
            <el-radio-group v-model="form.timeSlot">
              <el-radio label="上午">上午</el-radio>
              <el-radio label="下午">下午</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.info" type="textarea" placeholder="可选" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="submitAppointment">确认预约</el-button>
      </template>
    </el-dialog>
    <BottomNavigation />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs'
import BottomNavigation from '@/components/BottomNavigation.vue'
import { Calendar } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import TopHeader from '@/components/TopHeader.vue'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const defaultAvatar = 'https://cdn-icons-png.flaticon.com/512/4140/4140048.png'

const departments = ref([]) // 一级科室
const activeDeptId = ref(null)
const allDoctors = ref([]) // 所有医生
const doctors = ref([]) // 当前一级科室下所有医生
const doctorWorks = ref([]) // 当前一级科室下所有医生的排班
const dateList = ref([])
const activeDateIdx = ref(0)
const showDialog = ref(false)
const currentDoctor = ref(null)
const form = ref({
  name: '',
  telephone: '',
  day: '',
  timeSlot: '上午',
  info: ''
})
const availableDays = ref([])
const showCalendar = ref(false)
const calendarDate = ref(null)
const formRef = ref(null)
const showRecommendOnly = ref(false)

// 获取未来N天所有日期
const getAllFutureDates = (days = 14) => {
  const today = dayjs()
  return Array.from({ length: days }).map((_, i) => {
    const d = today.add(i, 'day')
  return {
      value: d.format('YYYY-MM-DD'),
      label: '周' + '日一二三四五六'[d.day()],
      text: d.format('DD')
  }
})
}

// 1. 加载一级科室
onMounted(async () => {
// 获取一级科室
  const res = await axios.get('http://localhost:8080/hospital5_war/department/findByLeve?leve=1')
  departments.value = res.data
  // 获取所有医生
  const doctorRes = await axios.get('http://localhost:8080/hospital5_war/doctor/findAll')
  allDoctors.value = doctorRes.data
  if (departments.value.length) {
    selectDept(departments.value[0].departmentId)
  }
  // 新增：如果带有success=1参数，弹窗提示
  if (route.query.success === '1') {
    ElMessage.success('挂号成功！')
    // 清除参数，防止重复弹窗
    router.replace({ path: '/yonghu/online-registration', query: {} })
  }
  // 生成未来14天所有日期
  dateList.value = getAllFutureDates(14)
})

const selectDept = async (deptId) => {
  activeDeptId.value = deptId
  // 当前一级科室下所有医生
  const docs = allDoctors.value.filter(doc => doc.depart_id1 == deptId)
  doctors.value = docs
  // 查所有医生的排班
  let allWorks = []
  for (const doc of docs) {
    const res4 = await axios.get('http://localhost:8080/hospital5_war/doctorWork/findByDocId?docId=' + doc.doc_id)
    allWorks = allWorks.concat(res4.data.map(dw => ({ ...dw, doc_id: doc.doc_id })))
  }
  // 只保留今天及以后的排班
  const today = dayjs().startOf('day')
  const futureWorks = allWorks.filter(dw => dayjs(dw.day).isSameOrAfter(today))
  doctorWorks.value = futureWorks
  // 生成未来14天所有日期
  dateList.value = getAllFutureDates(14)
  activeDateIdx.value = 0
}

const selectDate = (idx) => {
  activeDateIdx.value = idx
}

const onCalendarChange = (val) => {
  if (val) {
    const d = dayjs(val)
    dateList.value = [{
      value: d.format('YYYY-MM-DD'),
      label: '周' + '日一二三四五六'[d.day()],
      text: d.format('DD')
    }]
    activeDateIdx.value = 0
  }
  showCalendar.value = false
}

// 右侧医生过滤：只显示当天有排班的医生（amwork或pmwork非空且不为'0'，且排班日期为今天及以后）
const filteredDoctors = computed(() => {
  const date = dateList.value[activeDateIdx.value]?.value
  if (!date) return []
  let docs = doctors.value
  if (showRecommendOnly.value) {
    docs = docs.filter(doc => doc.recommend == 1)
  }
  return docs.filter(doc => {
    return doctorWorks.value.some(dw =>
      dw.doc_id === doc.doc_id &&
      dayjs(dw.day).format('YYYY-MM-DD') === date &&
      ((dw.amwork && dw.amwork !== '0') || (dw.pmwork && dw.pmwork !== '0'))
    )
  })
})

// 获取医生当天余号
const getDoctorWorkLeft = (doc, type) => {
  const date = dateList.value[activeDateIdx.value]?.value
  const dw = doctorWorks.value.find(dw => dw.doc_id === doc.doc_id && dayjs(dw.day).format('YYYY-MM-DD') === date)
  if (!dw) return '-'
  if (type === 'am') return (dw.amwork && dw.amwork !== '0') ? (dw.count_left ?? '-') : '-'
  if (type === 'pm') return (dw.pmwork && dw.pmwork !== '0') ? (dw.count_left ?? '-') : '-'
  return '-'
}

// 预约弹窗
const openAppointmentDialog = (doc) => {
  currentDoctor.value = doc
  form.value.name = userStore.userInfo?.realName || ''
  form.value.telephone = userStore.userInfo?.telephone || ''
  // 直接用当前高亮日期
  form.value.day = dateList.value[activeDateIdx.value]?.value || ''
  form.value.timeSlot = '上午'
  form.value.info = ''
  showDialog.value = true
}

// 电话校验方法
const validatePhone = (rule, value, callback) => {
  if (!/^1\d{10}$/.test(value)) {
    callback(new Error('请输入11位手机号'));
  } else {
    callback();
  }
};

// 预约校验：只要amwork或pmwork非空且不为'0'即可预约
const submitAppointment = async () => {
  if (!form.value.name || !form.value.telephone || !form.value.day) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (formRef.value) {
    try {
      await formRef.value.validate()
    } catch (e) {
      return
    }
  }
  try {
    await axios.post('http://localhost:8080/hospital5_war/patientDoctor/addPatientDoctor', {
      patientId: userStore.userInfo?.userId || '',
      name: form.value.name,
      docId: currentDoctor.value.doc_id,
      telephone: form.value.telephone,
      day: form.value.day,
      departId2: currentDoctor.value.depart_id2,
      info: `${form.value.timeSlot} - ${form.value.info || '无备注'}`,
      diagnosisStatus: 0
    }, {
      headers: { 'Content-Type': 'application/json' }
    })

    // 新增：挂号成功后，号源count_left减一
    // 1. 查找当前医生当天的号源
    const dwRes = await axios.get('http://localhost:8080/hospital5_war/doctorWork/findByDocIdAndDay', {
      params: {
        docId: currentDoctor.value.doc_id,
        day: form.value.day
      }
    })
    const doctorWork = dwRes.data
    if (doctorWork && doctorWork.count_left > 0) {
      doctorWork.count_left = doctorWork.count_left - 1
      await axios.post('http://localhost:8080/hospital5_war/doctorWork/update', doctorWork, {
        headers: { 'Content-Type': 'application/json' }
      })
    }

    showDialog.value = false
    // 跳转到支付页面并传递医生和科室信息
    router.push({
      path: '/yonghu/payment',
      query: {
        doctor_name: currentDoctor.value.doc_name,
        department_name: departments.value.find(dept => dept.departmentId === activeDeptId.value)?.departmentName || '内科',
        real_name: form.value.name,
        amount: '20.00'
      }
    })
  } catch (e) {
    if (e.response && e.response.status === 409) {
      ElMessage.error(e.response.data || '请勿重复挂号')
      showDialog.value = false
      router.push('/yonghu/online-registration')
    } else {
      ElMessage.error('挂号失败，请重试')
    }
  }
}

const goToProfile = () => {
  router.push('/yonghu/profile-info')
}
</script>

<style scoped>
.reg-page {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 60px;
  padding-top: 70px;
}
.reg-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #e6f0ff;
  color: #165DFF;
  font-size: 16px;
  padding: 14px 18px 10px 18px;
  font-weight: 500;
}
.id-link {
  color: #409eff;
  font-size: 15px;
  cursor: pointer;
}
.reg-main {
  display: flex;
  height: calc(100vh - 60px - 48px);
}
.dept-list {
  width: 110px;
  background: #fff;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
  padding: 0;
}
.dept-item {
  padding: 18px 0 18px 0;
  text-align: center;
  color: #666;
  font-size: 15px;
  cursor: pointer;
  border-left: 3px solid transparent;
  transition: background 0.2s, color 0.2s, border 0.2s;
}
.dept-item.active {
  background: #e6f0ff;
  color: #165DFF;
  border-left: 3px solid #165DFF;
  font-weight: bold;
}
.reg-content {
  flex: 1;
  padding: 0 10px;
  overflow-y: auto;
}
.date-bar {
  display: flex;
  gap: 8px;
  margin: 8px 0 12px 0;
  overflow-x: auto;
}
.date-item {
  min-width: 54px;
  background: #fff;
  border-radius: 8px;
  text-align: center;
  color: #666;
  font-size: 14px;
  padding: 6px 0 4px 0;
  cursor: pointer;
  border: 2px solid transparent;
  transition: background 0.2s, color 0.2s, border 0.2s;
}
.date-item.active {
  background: #165DFF;
  color: #fff;
  border: 2px solid #165DFF;
  font-weight: bold;
}
.doctor-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.doctor-card {
  display: flex;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(22,93,255,0.08);
  padding: 14px 12px;
  align-items: center;
  cursor: pointer;
  transition: box-shadow 0.2s, transform 0.1s;
}
.doctor-card:hover {
  box-shadow: 0 6px 24px rgba(22,93,255,0.16);
  transform: translateY(-2px) scale(1.03);
}
.doc-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 14px;
  background: #e6f0ff;
}
.doc-info {
  flex: 1;
}
.doc-name {
  font-size: 16px;
  font-weight: bold;
  color: #165DFF;
  margin-bottom: 2px;
}
.doc-title {
  font-size: 13px;
  color: #888;
  margin-left: 6px;
}
.doc-nums {
  font-size: 13px;
  color: #faad14;
  margin-bottom: 2px;
}
.calendar-btn {
  margin-left: 8px;
  vertical-align: middle;
  background: #fff;
  border: 1px solid #e6e6e6;
  box-shadow: none;
}
</style>